package com.kaithan.framework.common.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 建类说明：spring上下文工具类
 *
 * @author 中国印
 * @since 2022年12月21日 13:33:39
 */
@Component
public class SpringContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    
    public static ApplicationContext getApplicationContext() {
        return SpringContext.applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanId) {
        return (T) applicationContext.getBean(beanId);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    /**
     * 获取Spring装配的bean的名称
     */
    public static Map<String, ?> getBeansOfType(Class<?> requiredType) {
        return applicationContext.getBeansOfType(requiredType);
    }

    /**
     * Spring容器启动后，会把 applicationContext 给自动注入进来，然后我们把 applicationContext 赋值到静态变量中，方便后续拿到容器对象
     * @see ApplicationContextAware#setApplicationContext(ApplicationContext)
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContext.applicationContext = applicationContext;
    }

    /**
     * 获取Spring装配的bean的名称
     */
    public static String[] getBeanNameAll() {
        return applicationContext.getBeanDefinitionNames();
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义，则返回true
     *
     * @param name bean名称
     * @return boolean
     */
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

}
